package controllers;

import java.awt.event.ActionEvent;
import java.util.Vector;

import dialogs.DeleteTupleDialog;
import dialogs.InsertTupleDialog;

import models.ShipItemModel;

import system.View;

public class ShipItemController extends AbstractMenuItemController {
	private ShipItemModel ship_item = new ShipItemModel();

	public ShipItemController(View v) {
		super(v);
		abstractModel = ship_item;
		ship_item.addExceptionListener(this);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String actionCommand = e.getActionCommand();

		if (actionCommand.equals("Remove Item from Shipment"))
			showDialogWindow(new DeleteTupleDialog(view, actionCommand, "Key",
					new String[] { "Shipment ID Number: ", "Item UPC: " }, this));
		else if (actionCommand.equals("Add Item to Shipment"))
			showDialogWindow(new InsertTupleDialog(view, actionCommand,
					"Item/Shipment",
					new String[] { "Shipment ID Number: ", " Item UPC: ",
							"Supplier's Price: ", "Quantity: ", }, this));
	}

	@Override
	public int validateInsert(Vector<String> s) {
		if (s.size() != 4)
			return VALIDATIONERROR;
		try {
			int upc;
			int sid;
			int supPrice;
			int quantity;

			if (s.get(0).trim().length() != 0)
				upc = Integer.valueOf(s.get(0).trim());
			else return VALIDATIONERROR;
			if (s.get(1).length() != 0)
				sid = Integer.valueOf(s.get(1).trim());
			else return VALIDATIONERROR;
			if (s.get(2).length() != 0)
				supPrice = Integer.valueOf((s.get(2).trim()));
			else return VALIDATIONERROR;
			if (s.get(3).length() != 0)
				quantity = Integer.valueOf(s.get(3).trim());
			else return VALIDATIONERROR;

			view.updateStatusBar("Inserting Item being shipped...");

			if (ship_item.insert(upc, sid, supPrice, quantity))
				return operationSuccess();
			else return operationFailure();
		} catch (NumberFormatException ex) {
			return VALIDATIONERROR;
		}
	}
	
	@Override
	public int validateDelete(Vector<String> s) {
		if (s.size() != 2)
			return VALIDATIONERROR;

		try {
			Integer sid, upc;

			if (s.get(0).trim().length() != 0)
				sid = Integer.valueOf(s.get(0).trim());
			else return VALIDATIONERROR;
			if (s.get(1).trim().length() != 0)
				upc = Integer.valueOf(s.get(0).trim());
			else return VALIDATIONERROR;

			view.updateStatusBar("Deleting item being shipped...");

			if (ship_item.delete(sid, upc)) return operationSuccess();
			else return operationFailure();
		} catch (NumberFormatException ex) {
			return VALIDATIONERROR;
		}
	}
}